package com.swm.julie.rest.crud.twitt.insert;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.PlatformLoggingMXBean;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swm.julie.rest.crud.twitt.TwittDocFormat;

@SuppressWarnings("serial")
public class InsertTwittServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");

		Map<String, String[]> params = req.getParameterMap();
		
		TwittDocFormat twitt = new TwittDocFormat();
		twitt.setId(new Long(params.get("id")[0]));
		twitt.setPostdate(params.get("postdate")[0]);
		twitt.setContents(params.get("contents")[0]);
		twitt.setLinkInfo(params.get("linkInfo")[0]);
		twitt.setPostUrl(params.get("url")[0]);
		
		InsertTwitt insert = new InsertTwitt(twitt);
		
		//Set the result of inserting the new twitt
		if(insert.insertTwiit(System.getProperty("user.dir") + "/tempNewTwitt"))
		{
			req.setAttribute("twitt", twitt);
			System.out.println("insert " + twitt.getId() + ", " + twitt.getContents());
		}else
		{
			//if inserting is fail, then attribute value is null
			req.setAttribute("twitt", null);
		}
		
		//Dispatch to the view page
		System.out.println("InsertTwittServlet.doPost() : Dispatch to insertResult.jsp");
		RequestDispatcher view = req.getRequestDispatcher("insertResult.jsp");
		view.forward(req, resp);
	}
}
